<template>
  <div
    style="border-radius: 5px; display: flex; height: auto; flex-wrap: wrap"
    :style="{ border: isInputFocus ? '1.5px solid #409eff' : '1.5px solid #dcdfe6' }"
  >
    <el-tag
      v-for="info in receiverInfos"
      :key="info.address"
      closable
      :disable-transitions="true"
      @close="handleDeleteTag(info)"
      style="
        color: black;
        margin-left: 5px;
        margin-top: 3px;
        margin-bottom: 3px;
        font-size: 10pt;
        height: 27px;
      "
      color="white"
    >
      <el-button
        :type="addressButtonType[info.type]"
        circle
        class="mr-1"
        size="small"
        style="width: 30px"
        @click="() => handleAddressTypeClick(info.id, info.type)"
        >{{ addressType[info.type] }}</el-button
      >
      <span>{{ info.name }}</span>
      <span style="color: #808080">&lt;{{ info.address }}>;</span>
    </el-tag>
    <div style="min-width: 270px; flex-grow: 1; display: flex">
      <el-input
        ref="inputRef"
        v-model="inputContent"
        style="flex-grow: 1"
        @keyup="onHanleInputKeyUp"
        @keydown="onHandleInputKeyDown"
        @focus="onHandleInputFocus"
        @blur="onHandleInputLostFocus"
        class="addressInput"
      />

      <el-button style="margin-left: auto" link v-if="isInputFocus">
        <Icon
          icon="ic:twotone-add-circle-outline"
          :size="20"
          style="color: #4691d4"
          @click="handleShowContact"
        />
      </el-button>
    </div>
    <el-popover
      placement="bottom-start"
      :width="400"
      :visible="popoverVisible"
      virtual-triggering
      :virtual-ref="inputRef"
      :show-arrow="false"
    >
      <Table
        ref="searchTableRef"
        :data="searchTableList"
        :columns="tableColumns"
        max-height="500"
        :show-header="false"
        :border="false"
        alignWhole="left"
        style="--el-table-border-color: none"
        @row-click="onhandleTableClick"
      >
        <template #name="{ row }">
          <span style="cursor: default">{{ row.name }}</span>
          <span style="cursor: default; color: #808080">&nbsp;&lt;{{ row.address }}></span>
        </template>
      </Table>
    </el-popover>
    <CustomerContactMailSelect ref="contactSelectRef" @success="selectContactMail" />
    <CustomerShow ref="customerShowRef" />
  </div>
</template>
<script setup name="MailReceiver" lang="ts">
import CustomerContactMailSelect from '@/views/customer/customer/CustomerContactMailSelect.vue'
import CustomerShow from '@/views/customer/customer/CustomerShow.vue'
import { isEmail } from '@pureadmin/utils'
import * as MailApi from '@/api/mailbox/mail'
const emit = defineEmits(['update:modelValue'])

const addressType = ['', '客户', '公海', '陌生']
const addressButtonType = ['', 'success', 'warning', 'info'] as any[]
const props = defineProps({
  modelValue: {
    type: Array,
    required: false
  }
})

const customerShowRef = ref()
const contactSelectRef = ref()
const searchTableRef = ref()
const isInputFocus = ref(false)
const inputContent = ref('')
const inputRef = ref()
const popoverVisible = ref(false)
const searchTableList = ref()

const tableColumns: TableColumnList = [
  {
    label: '名称',
    prop: 'name',
    slot: 'name'
  }
]

const receiverInfos = ref<any[]>([])

watch(
  () => props.modelValue,
  async (propModelValue: any[]) => {
    if (propModelValue != undefined) {
      receiverInfos.value = []
      inputContent.value = ''
      let queryInfo = [] as any[]
      propModelValue.forEach((item) => {
        if (item.name != '') {
          queryInfo.push({ address: item.address, name: item.name })
        } else inputContent.value = item.address
      })
      if (queryInfo.length > 0) {
        const contactInfos = await MailApi.getReceiverByAddresses(queryInfo)
        contactInfos.forEach((info) => {
          receiverInfos.value.push({
            name: info.name,
            address: info.address,
            type: info.type,
            contactId: info.id
          })
        })
      }
    }
  },
  { deep: true }
)

const onHandleInputFocus = () => {
  isInputFocus.value = true
  const content = inputContent.value.trim()
  loadTableReceiver(content)
}

const onHandleInputLostFocus = () => {
  setTimeout(() => {
    isInputFocus.value = false
  }, 100)
  popoverVisible.value = false
}

const onHandleInputKeyDown = (event) => {
  if (inputContent.value == '' && event.code == 'Backspace') {
    receiverInfos.value.pop()
    emit('update:modelValue', receiverInfos.value)
  }
}
const onHanleInputKeyUp = async (event) => {
  const content = inputContent.value.substring(0, inputContent.value.length - 1)
  if (event.code == 'Space' || event.code == 'Semicolon') {
    if (isEmail(content)) {
      const contactInfos = await MailApi.getReceiverByAddresses([
        { address: content, name: undefined }
      ])
      if (contactInfos.length > 0) {
        addReceiver(
          contactInfos[0].name,
          contactInfos[0].address,
          contactInfos[0].id,
          contactInfos[0].type
        )
      } else {
        addReceiver(content.slice(0, content.indexOf('@')), content, 0, 3)
      }
    }
  }
  loadTableReceiver(inputContent.value.trim())
  if (inputContent.value.trim() != '') {
    emit('update:modelValue', [
      ...receiverInfos.value,
      ...[{ name: '', address: inputContent.value }]
    ])
  } else {
    emit('update:modelValue', receiverInfos.value)
  }
}

const loadTableReceiver = async (content) => {
  if (content != '') {
    popoverVisible.value = true
    searchTableList.value = await MailApi.receiverMultiQuery({ multiOption: content })
  } else {
    popoverVisible.value = false
  }
}

const onhandleTableClick = (row) => {
  addReceiver(row.name, row.address, row.id, row.type)
  searchTableRef.value.getTableRef().setCurrentRow()
  inputRef.value.focus()
}

const addReceiver = (name, address, id, type) => {
  let isExists = false
  receiverInfos.value.forEach((info) => {
    if (info.address == address) isExists = true
  })
  if (!isExists) {
    receiverInfos.value.push({
      name: name,
      address: address,
      type: type,
      contactId: id
    })
  }
  inputContent.value = ''
  emit('update:modelValue', receiverInfos.value)
}

const handleDeleteTag = (info) => {
  receiverInfos.value.splice(receiverInfos.value.indexOf(info), 1)
  emit('update:modelValue', receiverInfos.value)
}

const handleAddressTypeClick = (id, type) => {
  if (type == 3) return
  customerShowRef.value.open(id)
}

const handleShowContact = () => {
  contactSelectRef.value.open()
}

const selectContactMail = (selectContactMail) => {
  selectContactMail.forEach((mail) => {
    addReceiver(
      mail.contact.name,
      mail.mailAddress,
      mail.id,
      mail.contact.customer.isFallPool ? 2 : 1
    )
  })
}
</script>
<style scoped>
:deep(.addressInput .el-input__wrapper) {
  box-shadow: none;
}
:deep(.el-table__cell) {
  padding: 5px 0 !important;
}
</style>
